<?php

/**
 * Implements hook_html_head_alter().
 * We are overwriting the default meta character type tag with HTML5 version.
 */
function amaze_html_head_alter(&$head_elements) {
  $head_elements['system_meta_content_type']['#attributes'] = array(
    'charset' => 'utf-8'
  );
  $head_elements['ie_edge'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'http-equiv' => 'X-UA-Compatible',
      'content' => 'IE=edge',
    ),
  );
  $head_elements['viewport'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'viewport',
      'content' => 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
    ),
  );
  $head_elements['webkit_renderer'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'renderer',
      'content' => 'webkit',
    ),
  );
}

function amaze_process_html(&$variables) {}

function amaze_preprocess_page(&$variables) {
  $variables['main_content_class_array'] = array();
  $variables['sidebar_first_class_array'] = array();
  $variables['sidebar_second_class_array'] = array();
  $has_sidebar_first = $has_sidebar_second = FALSE;

  $variables['main_menu'] = theme('links__system_main_menu', array(
    'links' => $variables['main_menu'],
    'attributes' => array(
      'id' => 'main-menu',
      'class' => array('am-nav', 'am-nav-pills', 'am-topbar-nav'),
    ),
  ));

  if ($variables['page']['sidebar_first']) {
    $has_sidebar_first = TRUE;
    $variables['sidebar_first_class_array'][] = 'am-u-md-3';
  }
  if ($variables['page']['sidebar_second']) {
    $has_sidebar_second = TRUE;
    $variables['sidebar_second_class_array'][] = 'am-u-md-3';
  }
  if ($has_sidebar_first && $has_sidebar_second) {
    $variables['main_content_class_array'] = array('am-u-md-6', 'am-u-md-push-3');
    $variables['sidebar_first_class_array'][] = 'am-u-md-pull-6';
  }
  elseif ($has_sidebar_first || $has_sidebar_second) {
    $variables['main_content_class_array'][] = 'am-u-md-9';
    $variables['sidebar_first_class_array'][] = 'am-u-md-pull-9';   

    if ($has_sidebar_first) {
      $variables['main_content_class_array'][] = 'am-u-md-push-3';
    } 
  }
  else {
    $variables['main_content_class_array'][] = 'am-u-md-12';
  }

}

function amaze_css_alter(&$css) {
  foreach ($css as $filename => $data) {
    if (strpos($filename, 'modules') !== false) {
      // unset($css[$filename]);
    }
  }
}

function amaze_js_alter(&$js) {
  $extras = array(
    'sites/all/modules/contrib/ctools/js/modal.js' => drupal_get_path('theme', 'amaze').'/js/modules/ctools/js/modal.js',
  );
  foreach($extras as $old => $new) {
    if (isset($js[$old])) {
      // $js[$new] = $js[$old];
      // $js[$new]['data'] = $new;
      // unset($js[$old]);
      drupal_add_js($new);
    }
  }
}

function amaze_process_page(&$variables) {
  $variables['main_content_classes'] = implode(' ', $variables['main_content_class_array']);
  $variables['sidebar_first_classes'] = implode(' ', $variables['sidebar_first_class_array']);
  $variables['sidebar_second_classes'] = implode(' ', $variables['sidebar_second_class_array']);
}

/**
 * Return a themed breadcrumb trail.
 *
 * @param $breadcrumb
 *   An array containing the breadcrumb links.
 * @return a string containing the breadcrumb output.
 */
function amaze_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    $heading = '<h2 class="element-invisible">' . t('You are here') . '</h2>';
    // Uncomment to add current page to breadcrumb
	// $breadcrumb[] = drupal_get_title();
    return '<nav class="breadcrumb">' . $heading . implode(' » ', $breadcrumb) . '</nav>';
  }
}

/**
 * Duplicate of theme_menu_local_tasks() but adds clearfix to tabs.
 */
function amaze_menu_local_tasks(&$variables) {
  $output = '';

  if (!empty($variables['primary'])) {
    $variables['primary']['#prefix'] = '<h2 class="element-invisible">' . t('Primary tabs') . '</h2>';
    $variables['primary']['#prefix'] .= '<ul class="tabs primary clearfix">';
    $variables['primary']['#suffix'] = '</ul>';
    $output .= drupal_render($variables['primary']);
  }
  if (!empty($variables['secondary'])) {
    $variables['secondary']['#prefix'] = '<h2 class="element-invisible">' . t('Secondary tabs') . '</h2>';
    $variables['secondary']['#prefix'] .= '<ul class="tabs secondary clearfix">';
    $variables['secondary']['#suffix'] = '</ul>';
    $output .= drupal_render($variables['secondary']);
  }
  return $output;
}

/**
 * Override or insert variables into the node template.
 */
function amaze_preprocess_node(&$variables) {
  // $variables['submitted'] = t('Published by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
  $node_type = $variables['type'];

  $variables['submitted'] = $variables['name'] . ' 发表于 ' . date('Y-m-d', $variables['created']);
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    $variables['classes_array'][] = 'node-full';
  }

  array_splice($variables['theme_hook_suggestions'], 1, 0, 'node__'. $variables['type']. '__'. $variables['view_mode']);

  $func = 'amaze_preprocess_node_'.$node_type;
  if (function_exists($func)) {
    $func($variables);
  }
}

/**
 * Preprocess variables for region.tpl.php
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("region" in this case.)
 */
function amaze_preprocess_region(&$variables, $hook) {
  // Use a bare template for the content region.
  if ($variables['region'] == 'content') {
    $variables['theme_hook_suggestions'][] = 'region__bare';
  }
}

/**
 * Override or insert variables into the block templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("block" in this case.)
 */
function amaze_preprocess_block(&$variables, $hook) {
  // Use a bare template for the page's main content.
  if ($variables['block_html_id'] == 'block-system-main') {
    $variables['theme_hook_suggestions'][] = 'block__bare';
  }
  $variables['title_attributes_array']['class'][] = 'block-title';
}

/**
 * Override or insert variables into the block templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("block" in this case.)
 */
function amaze_process_block(&$variables, $hook) {
  // Drupal 7 should use a $title variable instead of $block->subject.
  $variables['title'] = $variables['block']->subject;
}

function amaze_comment_view_alter(&$build, $type) {
  // dpm($build);
}

/**
 * Implements hook_preprocess_comment().
 */

function amaze_preprocess_comment(&$variables) {
  $comment = $variables['comment'];

  $filepath = _get_user_avatar_uri($comment);
  $variables['user_picture_url'] = file_create_url($filepath);

  $variables['parent_comment'] = '';
  if ($comment->pid) {
    $parent = comment_load($comment->pid);
    $msg = $parent->comment_body['und'][0]['safe_value'];
    $author = $parent->name;
    $variables['content']['comment_body'][0]['#markup'] .= " //<a>@{$author}</a>: $msg";
    $variables['parent_comment'] = "@{$author}：$msg";
  }
}

/**
 * Implements hook_preprocess_comment_wrapper().
 */
function amaze_preprocess_comment_wrapper(&$variables) {
  $comments = &$variables['content']['comments'];
  foreach (element_children($comments) as $key) {
    if (isset($comments[$key]['comment_body'])) {
      $comments[$key]['#prefix'] = '';
      // $comments[$key]['#suffix'] = '<br>';
    }
  }
  // dpm($comments);
  // $comments['#prefix'] = '<ul class="am-comments-list">';
  // $comments['#suffix'] = '</ul>';

  // if (isset($comments['dummyComment'])) {
  //   $comments['#suffix'] .= render($comments['dummyComment']);
  // }
}

/**
 * theme_comment_form
 */
function amaze_comment_form(&$variables) {
  global $user;
  // dpm($variables);
  hide($variables['form']['author']);
  hide($variables['form']['actions']['preview']);
  
  $variables['form']['actions']['submit']['#attributes']['class'][] = 'am-btn-success';
  $variables['form']['actions']['submit']['#weight'] = 100;
  $variables['form']['actions']['submit']['#value'] = '发布';
  $variables['form']['actions']['cancel']['#type'] = 'link';

  $variables['form']['comment_body']['und'][0]['value']['#attributes']['placeholder'] = '说点什么吧……';

  $variables['form']['#prefix'] = '<div class="am-comment-main">';
  $variables['form']['#suffix'] = '</div>';

  $avatar_uri = _get_user_avatar_uri();
  $avatar = "<img class='am-comment-avatar' src='$avatar_uri' >";

  return  $avatar.'<div class="am-comment-main">' . drupal_render_children($variables['form']) . '</div>';
}

/**
 * Changes the search form to use the "search" input element of HTML5.
 */
function amaze_preprocess_search_block_form(&$vars) {
  $vars['search_form'] = str_replace('type="text"', 'type="search"', $vars['search_form']);
}

function amaze_form_user_login_alter(&$form, &$form_state) {
  $form['#attributes']['class'] = array('form-user-login');
  foreach (array('name', 'pass') as $key) {
    // $form[$key]['#attributes']['placeholder'] = $form[$key]['#description'];
    unset($form[$key]['#description']);
  }
}

function amaze_form_user_register_form_alter(&$form, &$form_state, &$js_rules) {
}



function amaze_form($variables) {
  $element = $variables ['element'];
  if (isset($element ['#action'])) {
    $element ['#attributes']['action'] = drupal_strip_dangerous_protocols($element ['#action']);
  }
  element_set_attributes($element, array('method', 'id'));
  if (empty($element ['#attributes']['accept-charset'])) {
    $element ['#attributes']['accept-charset'] = "UTF-8";
  }
  $element['#attributes']['class'][] = 'am-form';
  // Anonymous DIV to satisfy XHTML compliance.
  return '<form' . drupal_attributes($element ['#attributes']) . '><div>' . $element ['#children'] . '</div></form>';
}

/**
 * Overrides theme_form_element().
 */
function amaze_form_element(&$variables) {

  $element = &$variables['element'];
  $is_checkbox = FALSE;
  $is_radio = FALSE;

  // This function is invoked as theme wrapper, but the rendered form element
  // may not necessarily have been processed by form_builder().
  $element += array(
    '#title_display' => 'before',
  );

  // Add element #id for #type 'item'.
  if (isset($element['#markup']) && !empty($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }

  // Check for errors and set correct error class.
  if (isset($element['#parents']) && form_get_error($element)) {
    $attributes['class'][] = 'error';
  }

  if (!empty($element['#type'])) {
    $attributes['class'][] = 'form-type-' . strtr($element['#type'], '_', '-');
  }
  if (!empty($element['#name'])) {
    $attributes['class'][] = 'form-item-' . strtr($element['#name'], array(
        ' ' => '-',
        '_' => '-',
        '[' => '-',
        ']' => '',
      ));
  }
  // Add a class for disabled elements to facilitate cross-browser styling.
  if (!empty($element['#attributes']['disabled'])) {
    $attributes['class'][] = 'form-disabled';
  }
  if (!empty($element['#autocomplete_path']) && drupal_valid_path($element['#autocomplete_path'])) {
    $attributes['class'][] = 'form-autocomplete';
  }
  $attributes['class'][] = 'form-item';

  // See http://getbootstrap.com/css/#forms-controls.
  if (isset($element['#type'])) {
    if ($element['#type'] == "radio") {
      $attributes['class'][] = 'am-radio';
      $is_radio = TRUE;
    }
    elseif ($element['#type'] == "checkbox") {
      $attributes['class'][] = 'am-checkbox';
      $is_checkbox = TRUE;
    }
    else {
      $attributes['class'][] = 'am-form-group am-form-group-sm';
    }
  }

  $output = '<div' . drupal_attributes($attributes) . '>' . "\n";

  // If #title is not set, we don't display any label or required marker.
  if (!isset($element['#title'])) {
    $element['#title_display'] = 'none';
  }

  $prefix = '';
  $suffix = '';
  if (isset($element['#field_prefix']) || isset($element['#field_suffix'])) {
    // Determine if "#input_group" was specified.
    if (!empty($element['#input_group'])) {
      $prefix .= '<div class="input-group">';
      $prefix .= isset($element['#field_prefix']) ? '<span class="input-group-addon">' . $element['#field_prefix'] . '</span>' : '';
      $suffix .= isset($element['#field_suffix']) ? '<span class="input-group-addon">' . $element['#field_suffix'] . '</span>' : '';
      $suffix .= '</div>';
    }
    else {
      $prefix .= isset($element['#field_prefix']) ? $element['#field_prefix'] : '';
      $suffix .= isset($element['#field_suffix']) ? $element['#field_suffix'] : '';
    }
  }

  switch ($element['#title_display']) {
    case 'before':
    case 'invisible':
      $output .= ' ' . theme('form_element_label', $variables);
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
      break;

    case 'after':
      if ($is_radio || $is_checkbox) {
        $output .= ' ' . $prefix . $element['#children'] . $suffix;
      }
      else {
        $variables['#children'] = ' ' . $prefix . $element['#children'] . $suffix;
      }
      $output .= ' ' . theme('form_element_label', $variables) . "\n";
      break;

    case 'none':
    case 'attribute':
      // Output no label and no required marker, only the children.
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
      break;
  }

  if (isset($element['#description'])) {
    $output .= '<p class="am-form-help">' . $element['#description'] . "</p>\n";
  }

  $output .= "</div>\n";

  return $output;
}

function amaze_form_element_label(&$variables) {
  $element = $variables['element'];

  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // Determine if certain things should skip for checkbox or radio elements.
  $skip = (isset($element['#type']) && ('checkbox' === $element['#type'] || 'radio' === $element['#type']));

  // If title and required marker are both empty, output no label.
  if ((!isset($element['#title']) || $element['#title'] === '' && !$skip) && empty($element['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

  $title = filter_xss_admin($element['#title']);

  $attributes = array('class' => array('am-form-label'));

  // Style the label as class option to display inline with the element.
  if ($element['#title_display'] == 'after' && !$skip) {
    $attributes['class'][] = $element['#type'];
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element['#title_display'] == 'invisible') {
    $attributes['class'][] = 'element-invisible';
  }

  if (!empty($element['#id'])) {
    $attributes['for'] = $element['#id'];
  }

  // Insert radio and checkboxes inside label elements.
  $output = '';
  if (isset($variables['#children'])) {
    $output .= $variables['#children'];
  }

  // Append label.
  $output .= $t('!title !required', array('!title' => $title, '!required' => $required));

  // The leading whitespace helps visually separate fields from inline labels.
  return ' <label' . drupal_attributes($attributes) . '>' . $output . "</label>\n";
}

function amaze_textfield($variables) {
  $element = $variables ['element'];
  $element['#attributes']['type'] = 'text';
  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
  _form_set_class($element, array('form-text', 'am-form-field'));

  $extra = '';
  if ($element['#autocomplete_path'] && !empty($element ['#autocomplete_input'])) {
    drupal_add_library('system', 'drupal.autocomplete');
    $element ['#attributes']['class'][] = 'form-autocomplete';

    $attributes = array();
    $attributes['type'] = 'hidden';
    $attributes['id'] = $element ['#autocomplete_input']['#id'];
    $attributes['value'] = $element ['#autocomplete_input']['#url_value'];
    $attributes['disabled'] = 'disabled';
    $attributes['class'][] = 'autocomplete';
    $extra = '<input' . drupal_attributes($attributes) . ' />';
  }

  $output = '<input' . drupal_attributes($element ['#attributes']) . ' />';

  if (isset($element['#description'])) {
    $attributes = array(
      'id' => $element['#attributes']['id'].'-desc',
      'class' => 'form-text-description',
    );
    $output .= '<p '. drupal_attributes($attributes) .'>'. $element['#description'] .'</p>';
  }

  return $output . $extra;
}

function amaze_password($variables) {
  $element = $variables ['element'];
  $element ['#attributes']['type'] = 'password';
  element_set_attributes($element, array('id', 'name', 'size', 'maxlength'));
  _form_set_class($element, array('form-text', 'am-form-field'));

  return '<input' . drupal_attributes($element ['#attributes']) . ' />';
}

/**
 * Overrides theme_button().
 */
function amaze_button($variables) {
  $element = $variables['element'];
  $label = $element['#value'];
  element_set_attributes($element, array('id', 'name', 'value', 'type'));

  $element['#attributes']['class'][] = 'am-btn';

  // If a button type class isn't present then add in default.
  $button_classes = array(
    'am-btn-default',
    'am-btn-primary',
    'am-btn-success',
    'am-btn-info',
    'am-btn-warning',
    'am-btn-danger',
    'am-btn-link',
  );
  $class_intersection = array_intersect($button_classes, $element['#attributes']['class']);
  if (empty($class_intersection)) {
    $element['#attributes']['class'][] = 'am-btn-default';
  }

  // Add in the button type class.
  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];

  // This line break adds inherent margin between multiple buttons.
  return '<button' . drupal_attributes($element['#attributes']) . '>' . $label . "</button>\n";
}